﻿using ExcellOnServices.Models;
using ExcellOnServices.Models.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace ExcellOnServices.Controllers
{
	public class StoreController : BaseController
	{
		public ActionResult Index(int? categoryId = null, string search = null, int? page = 1) {
			// Retrieve Prodcuts
			List<Product> products = CacheHelper.getProductList(db);

			// Retrieve Categories
			List<Category> categories = CacheHelper.getCategoryList(db);

			// Filter by category
			categoryId = categoryId ?? 0;			
			if (categoryId != 0) {
				Category category = (from c in categories where c.Id == categoryId select c).FirstOrDefault();
				if (category == null) {
					return RedirectToAction("Index", new { categoryId = 0, search = search, page = 1 });
				}

				products = (from p in products where p.Category_Id == categoryId select p).ToList();
			}

			// Search for products
			if (search != null) {
				ViewBag.search = search;
				search = search.ToLower().Trim();
				products = (from p in products
							where (p.Name != null && p.Name.ToLower().Contains(search))
								|| (p.Description != null && p.Description.ToLower().Contains(search))
							select p).ToList();
			}

			int pageSize = 8;
			int pageNumber = (page ?? 1);
			IPagedList<Product> pagedProducts = products.ToPagedList(pageNumber, pageSize);

			ViewBag.categoryId = (products == null || categoryId == null) ? 0 : categoryId;
			ViewBag.categories = categories;
			ViewBag.products = pagedProducts;

			return View(pagedProducts);
		}

		public ActionResult GetModalContactBody(int? productId = null) {
			Product product = null;
			if (productId != null) {
				product = (from p in CacheHelper.getProductList(db) where p.Id == productId select p).FirstOrDefault();
			}

			return PartialView("_PartialModalContactBody", product);
		}
	}
}